package com.haiyou.common.interceptor;

import com.haiyou.common.constant.MessageCode;
import com.haiyou.common.constant.RedisKeys;
import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Token拦截器
 */

@Component
@Slf4j
@Order(1)
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Environment env;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从header中获取token
        String token = request.getHeader("token");
        //token为空
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(MessageCode.NO_LOGIN.getCode(), "未授权,请重新登录");
        }

        String defaultValue = env.getProperty("swagger.defaultValue");
        if (defaultValue != null && defaultValue.equals(token)) {
            return true;
        }

        String userAccountKey = RedisKeys.getUserAccountKey(token);
        //查询token信息
        String tokenEntity = redisUtil.get(userAccountKey);

        if (tokenEntity == null) {
            throw new BusinessException(MessageCode.NO_AUTH.getCode(), "授权失效,请重新登录");
        }

        redisUtil.set(userAccountKey, tokenEntity, RedisKeys.USER_ACCOUNT_EXPIRE, TimeUnit.SECONDS);
        return true;
    }
}
